package com.codemart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codemart.common.R;
import com.codemart.component.RedisCache;
import com.codemart.constant.JwtHeaderConstant;
import com.codemart.constant.MessageConstant;
import com.codemart.constant.ProjectWebStatusCodeConstant;
import com.codemart.dto.*;
import com.codemart.exceptions.ServiceException;
import com.codemart.mapper.LoginMapper;
import com.codemart.service.LoginService;
import com.codemart.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Service
public class UserLoginServiceImpl implements LoginService {

    @Autowired
    LoginMapper loginMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public R login(UserLoginDTO userLogin) {

        // 使用 CompletableFuture 并行执行数据库查询
        CompletableFuture<UserResultDTO> userFuture = CompletableFuture.supplyAsync(() -> {
            return loginMapper.selectByUsername(userLogin.getUsername(), userLogin.getPassword());
        });

        CompletableFuture<List<UserRoleDTO>> userRoleFuture = CompletableFuture.supplyAsync(() -> {
            return loginMapper.selectByUsernameAndRole(userLogin.getUsername());
        });

        /**
         * @龚英杰 20250324
         * String role_json = "{\"page\":" + r_json + "}";
         */
        UserResultDTO user = loginMapper.selectByUsername(userLogin.getUsername(),userLogin.getPassword());
                if(Objects.isNull(user)){
                    throw new ServiceException(ProjectWebStatusCodeConstant.NOT_HAVE_ROLE,MessageConstant.USERNAME_OR_PASSWORD_IS_ERROR);
                }

        //        获取角色
                List<UserRoleDTO> userRole = loginMapper.selectByUsernameAndRole(userLogin.getUsername());
                String r_json = JSON.toJSONString(userRole);
                String role_json = ("{\"page\":"+r_json+"}");

                //生成token
                String userId = user.getU_id().toString();
                String jwt = JwtUtil.createJWT(userId);
        //        authenticate存入redis
                redisCache.setCacheObject("user_id:"+userId,role_json,2, TimeUnit.HOURS);

                HashMap<String,Object> map = new HashMap<>();
                map.put(JwtHeaderConstant.TOKEN_NAME_LOWER,jwt);
                map.put("page",userRole);

                return R.success(map, MessageConstant.LOGIN_SUCCESS);


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R register(UserRegisterDTO userRegister) {
        String un = loginMapper.showUserName(userRegister.getUsername());
        if(!Objects.equals(un, userRegister.getUsername())){
            loginMapper.register(userRegister,loginMapper);
            return R.success(MessageConstant.REGISTER_IS_SUCCESS);
        }else{
            return R.error(MessageConstant.USERNAME_IS_EXISTS);
        }
    }
}
